/**
 * 有道智云TTS文本转语音接口
 * @param {Object} params 请求参数
 * @param {string} params.appKey 应用ID
 * @param {string} params.appSecret 应用密钥
 * @param {string} params.q 待合成文本（UTF-8编码长度≤2048）
 * @param {string} params.voiceName 发言人名字
 * @param {string} [params.format='mp3'] 音频格式
 * @param {string} [params.speed='1'] 语速(0.5~2.0)
 * @param {string} [params.volume='1.00'] 音量(0.50~5.00)
 * @returns {Promise<Blob>} 音频文件Blob对象
 */

// import crypto from "crypto";
async function youdaoTTS(params) {
  const {
    appKey,
    appSecret,
    q,
    voiceName,
    format = "mp3",
    speed = "1",
    volume = "1.00",
  } = params;

  // 验证输入文本长度
  const encoder = new TextEncoder();
  const encodedText = encoder.encode(q);
  if (encodedText.length > 2048) {
    throw new Error("文本长度超过2048字节限制");
  }

  // 生成请求参数
  const salt = crypto.randomUUID();
  const curtime = Math.floor(Date.now() / 1000).toString();

  // 计算input
  let input;
  if (q.length > 20) {
    input = q.substring(0, 10) + q.length + q.substring(q.length - 10);
  } else {
    input = q;
  }

  // 生成签名
  const signStr = appKey + input + salt + curtime + appSecret;
  const signBuffer = await crypto.subtle.digest(
    "SHA-256",
    new TextEncoder().encode(signStr)
  );
  const signArray = Array.from(new Uint8Array(signBuffer));
  const signHex = signArray
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");

  // 构建表单数据
  const formData = new FormData();
  formData.append("q", q);
  formData.append("appKey", appKey);
  formData.append("salt", salt);
  formData.append("sign", signHex);
  formData.append("signType", "v3");
  formData.append("curtime", curtime);
  formData.append("format", format);
  formData.append("speed", speed);
  formData.append("volume", volume);
  formData.append("voiceName", voiceName);

  // 发送请求
  const response = await fetch("https://openapi.youdao.com/ttsapi", {
    method: "POST",
    body: formData,
  });

  // 处理响应
  const contentType = response.headers.get("Content-Type");
  if (contentType.includes("application/json")) {
    const errorData = await response.json();
    throw new Error(
      `TTS请求失败: ${errorData.errorCode} - ${errorData.message}`
    );
  }

  return await response.blob();
}

// 使用示例
async function generateSpeech(word) {
  try {
    const audioBlob = await youdaoTTS({
      appKey: "37f0b99a50c5487a",
      appSecret: "kZfwOflKNsAf9qmRyaxE4rBI4tnKuCK3",
      q: word,
      voiceName: "youxiaoqin",
      speed: "1.2",
      volume: "1.5",
    });

    // 创建音频播放
    const audioUrl = URL.createObjectURL(audioBlob);
    return audioUrl;
    // const audio = new Audio(audioUrl);
    // audio.play();

    // // 下载音频
    // const downloadLink = document.createElement("a");
    // downloadLink.href = audioUrl;
    // downloadLink.download = "audio.mp3";
    // downloadLink.click();
  } catch (error) {
    console.error("语音合成失败:", error);
  }
}

// 调用示例
export { generateSpeech };
